package middleware

import (
	"encoding/base64"
	"encoding/json"
	"gin/response"
	"gin/service"
	"gin/types"
	"github.com/gin-gonic/gin"
	"log"
	"strings"
)

// Auth 中间件，检查token
func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		xUserinfo := ctx.Request.Header.Get("x-userinfo")
		xUserinfo = strings.Trim(xUserinfo, " ")
		if xUserinfo == "" {
			response.Fail(ctx, nil, "Invalid token!")
			return
		}
		userInfoBytes, err := base64.StdEncoding.DecodeString(xUserinfo)
		if err != nil {
			log.Println("decode xuserinfo error " + xUserinfo)
			response.Fail(ctx, nil, "Invalid token!"+err.Error())
			return
		}

		var userInfo types.UserInfoHeader
		err = json.Unmarshal(userInfoBytes, &userInfo)

		if err != nil {
			log.Println("decode xuserinfo error " + xUserinfo)
			response.Fail(ctx, nil, "Invalid token!"+err.Error())
			return
		}

		if userInfo.Id <= 0 {
			response.Fail(ctx, nil, "Invalid token!")
			return
		}
		saasUserId, _ := service.GetSaasUserIdByUnionId(userInfo.Id)
		userInfo.SaasUserId = saasUserId
		userInfo.XU = xUserinfo
		ctx.Set("userInfo", userInfo)
		ctx.Set("user_id", userInfo.Id)
		ctx.Set("saas_user_id", saasUserId)
		ctx.Set("phone", userInfo.Phone)
		ctx.Set("tenant_id", userInfo.TenantId)
		ctx.Set("x-userinfo", xUserinfo)

		return

	}
}
